<template>
  <div>
    <!-- 条件筛选 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always">
          <el-form :inline="true" :model="queryForm" ref="queryForm" class="demo-form-inline">
            <el-form-item label="菜单名" prop="menuName">
              <el-input v-model="queryForm.menuName" placeholder="菜单名"></el-input>
            </el-form-item>
            <el-form-item label="菜单类型" prop="menuType">
              <el-select v-model="queryForm.menuType" placeholder="菜单类型">
                <el-option label="菜单" value="0"></el-option>
                <el-option label="按钮" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="warning" @click="resetForm('queryForm')">重置</el-button>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 按钮操作 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always" style="text-align: left">
          <el-button type="primary" size="small" @click="addOrUpdate('')">新增菜单</el-button>
          <el-button type="danger" size="small" @click="batchDel">批量删除</el-button>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 数据列表 -->
    <el-row :gutter="24">
      <el-col :span="6">
        <el-card shadow="always">
          <el-tree :data="menuData" :props="defaultProps" :default-expand-all="true"></el-tree>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="always">
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="sortNum" label="顺序" width="100px"></el-table-column>
            <el-table-column prop="menuName" label="菜单名" sortable></el-table-column>
            <el-table-column prop="menuUrl" label="菜单地址"></el-table-column>
            <el-table-column prop="menuType" label="菜单类型">
              <template slot-scope="scope">
                <span>{{ scope.row.menuType === 0?'菜单' :'按钮'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="menuPerm" label="权限标识"></el-table-column>
            <el-table-column label="操作" width="130">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="addOrUpdate(scope.row.id)">编辑</el-button>
                <el-button type="text" size="small" @click="delData(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top: 10px; text-align: right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="dataCount">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" style="text-align: left;">
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="上级菜单" prop="pid" :label-width="formLabelWidth">
          <el-select v-model="addForm.pid" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名" prop="menuName" :label-width="formLabelWidth">
          <el-input v-model="addForm.menuName" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="菜单地址" prop="menuUrl" :label-width="formLabelWidth">
          <el-input v-model="addForm.menuUrl" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType" :label-width="formLabelWidth">
          <el-select v-model="addForm.menuType" placeholder="请选择">
            <el-option label="菜单" :value="0"></el-option>
            <el-option label="按钮" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限标识" prop="menuPerm" :label-width="formLabelWidth">
          <el-input v-model="addForm.menuPerm" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="菜单排序" prop="sortNum" :label-width="formLabelWidth">
          <el-input v-model="addForm.sortNum" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')" :loading="saveLoading">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {get, post} from '@/api/http.js'

  export default {
    name: "menu",

    // 页面加载就执行
    mounted: function () {
      this.getListData();
      this.getParentMenu();
      this.getMenuTree();
    },

    // 双向数据绑定
    data() {
      return {
        // 菜单树形结构数据
        menuData: [],

        // 表单数据邦迪
        queryForm: {
          menuName: '',
          menuType: '',
          current: 1,
          size: 10,
          sortBy: '',
          sortOrder: ''
        },

        // 表格数据
        tableData: [],

        // 列表多选数据ID集合
        selectIds: [],

        // 分页参数
        currentPage: 1,
        pageSize: 10,
        dataCount: 0,

        // 上级菜单
        options: [],

        // 添加或修改弹出框
        title: '添加菜单',
        bizId: '',
        dialogFormVisible: false,
        formLabelWidth: '120px',
        addForm: {
          pid: '',
          menuName: '',
          menuUrl: '',
          menuType: '',
          menuPerm: '',
          sortNum: ''
        },
        // 表单校验
        rules: {
          menuName: [
            {required: true, message: '请输入菜单名', trigger: 'blur'},
          ],
          menuUrl: [
            {required: true, message: '请输入菜单地址', trigger: 'blur'},
          ],
          menuType: [
            {required: true, message: '请选择菜单类型', trigger: 'blur'},
          ],
          menuPerm: [
            {required: true, message: '请输入权限标识', trigger: 'blur'},
          ]
        },
        // 添加或修改数据保存loading
        saveLoading: false
      }
    },

    // 方法区
    methods: {

      // 查询菜单树形数据
      getMenuTree(){
        // 获取树形结构权限列表
        get('/admin/menu/tree', '')
          .then(res => {
            this.menuData = res.data;
          })
          .finally(() => {
            // 回显数据
            get('/admin/role/getRoleMenu/' + id, '')
              .then(res1 => {
                this.treeEcho = res1.data;
              })
          })
      },

      // 提交添加表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          // 表单验证是否通过
          if (valid) {
            this.saveLoading = true;
            let uri = "";
            let msg = "";
            if (this.bizId === '') {
              uri = "/admin/menu/add";
              msg = "恭喜你，菜单添加";
            } else {
              uri = "/admin/menu/update";
              msg = "恭喜你，菜单修改";
            }
            // 发起请求
            post(uri, this.addForm)
              .then(res => {
                this.$message({
                  message: msg + '成功',
                  type: 'success'
                });
              })
              .catch(err => {
                this.$message({
                  message: msg + '失败',
                  type: 'error'
                });
              })
              .finally(() => {  // 请求响应之后在执行
                this.saveLoading = false;
                // 关闭添加或修改弹出出框
                this.dialogFormVisible = false;
                this.bizId = '';
                this.resetForm('addForm');
                this.getListData();
                this.getMenuTree();
              })
          } else {
            return false;
          }
        });
      },

      // 提交查询表单
      onSubmit() {
        this.getListData();
        this.getMenuTree();
      },

      // 重置表单
      resetForm(formName) {
        this.dialogFormVisible = false;
        this.bizId = '';
        this.$refs[formName].resetFields();
      },

      // 添加或修改弹出对话框
      addOrUpdate(id) {
        this.getParentMenu();
        this.bizId = id;
        this.dialogFormVisible = true;
        if (id !== '') {
          this.title = "修改菜单";
          get("/admin/menu/get/" + id, '')
            .then(res => {
              this.addForm = res.data;
            })
            .catch(err => {

            })
            .finally(() => {

            })
        }
      },

      // 表格数据多选,获取ID
      handleSelectionChange(val) {
        // val 传给的是数组，里面放的是选中当前行的所有数据
        // console.info(val);
        // 声明一个空数组，将val遍历获取每一行数据的ID，放入集合
        let idsArr = new Array();
        val.forEach(row => {
          idsArr.push(row.id)
        });
        // 赋值给全局变量
        this.selectIds = idsArr;
      },

      // 批量删除
      batchDel() {
        if (this.selectIds.length === 0) {
          this.$message({
            type: 'warning',
            message: '请至少选择一条数据'
          });
          return;
        }
        // 调用删除方法
        this.delData(this.selectIds.toString());
      },

      // 删除数据
      delData(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {ids: id};
          get('/admin/menu/del', param)
            .then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              });
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: '删除失败'
              });
            }).finally(() => {
            this.getListData();
            this.getMenuTree();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 分页组件参数变动
      handleSizeChange(val) {
        this.queryForm.size = val;
        this.getListData();
      },
      handleCurrentChange(val) {
        this.queryForm.current = val;
        this.getListData();
      },

      // 获取列表数据
      getListData() {
        post("/admin/menu/list", this.queryForm)
          .then(res => {
            this.tableData = res.data.records;
            this.dataCount = res.data.total;
            this.pageSize = res.data.size;
            this.currentPage = res.data.current;
          })
          .catch(err => {

          })
          .finally(() => {

          })
      },

      // 获取菜单
      getParentMenu(){
        get("/admin/menu/info", '')
          .then(res =>{
            this.options = res.data;
          })
          .catch(err =>{

          })
      }
    }
  }
</script>

<style scoped>

</style>
